package nnweboa;

import java.io.File;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspWriter;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

public class Unitls {

	public static boolean hasCookie(HttpServletRequest request) {

		Cookie[] coarray = request.getCookies();
		for (int i = 0; i < coarray.length; i++) {
			Cookie item = coarray[i];
			String name = item.getName();

			if (name.compareToIgnoreCase("UserNameCookie") == 0) {
				return true;
			}
		}
		return false;
	}

	public static String getCookieName(HttpServletRequest request) {
		Cookie[] coarray = request.getCookies();
		for (int i = 0; i < coarray.length; i++) {
			Cookie item = coarray[i];
			String name = item.getName();

			if (name.compareToIgnoreCase("UserNameCookie") == 0) {
				return item.getValue();
			}
		}
		return "";
	}

	public static boolean isNoNtManager() throws SQLException,
			InstantiationException, IllegalAccessException,
			ClassNotFoundException {
		if (findmanager()) {
			return false;
		}
		return true;

	}

	private static boolean findmanager() throws SQLException,
			InstantiationException, IllegalAccessException,
			ClassNotFoundException {
		// TODO Auto-generated method stub
		List<Userinfo> alluser = findAll();
		for (int i = 0; i < alluser.size(); i++) {
			if (alluser.get(0).getRight() == User.NTManager) {
				return true;
			}
		}
		return false;
	}

	public static boolean testUser(Userinfo mail, String password) {
		String pass = mail.getPassword();
		if (pass.compareToIgnoreCase(password) == 0) {
			return true;
		}
		return false;

	}

	public static int getUserRightBycookieName(String cookiename, JspWriter out)
			throws SQLException, InstantiationException,
			IllegalAccessException, ClassNotFoundException, IOException {

		List<Userinfo> maillist = Unitls.findByMail(cookiename, out);
		int right = maillist.get(0).getRight();

		return right;
	}

	public static List<Userinfo> findByMail(String mail, JspWriter out)
			throws SQLException, InstantiationException,
			IllegalAccessException, ClassNotFoundException, IOException {

		ResultSet resut = SystemConfig.getInstance().getConnection()
				.createStatement().executeQuery("select * from userinfo");

		List<Userinfo> userinfo = new ArrayList<Userinfo>();
		while (resut.next()) {

			String mailtmp = resut.getString("mail");

			if (mailtmp.toLowerCase().trim()
					.compareToIgnoreCase(mail.toLowerCase().trim()) == 0) {

				Userinfo userinfoitem = new Userinfo();
				userinfoitem.setId(resut.getLong("id"));
				userinfoitem.setName(resut.getString("name"));
				userinfoitem.setmail(resut.getString("mail"));
				userinfoitem.setpassword(resut.getString("password"));
				userinfoitem.setright(resut.getInt("userright"));
				userinfoitem.setmodifydate(resut.getTimestamp("modifydate"));
				userinfoitem.setFreeze(resut.getInt("freeze"));
				userinfo.add(userinfoitem);
				break;
			}

		}
		return userinfo;
	}

	public static boolean testMail(String mail) {
		Pattern n = Pattern
				.compile("^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$");
		Matcher math = n.matcher(mail);
		if (math.find()) {
			return true;
		}

		return false;
	}

	public static String trytoSendtoMail(String nikename) {
		return Unitls.getPassword();

	}

	public static void Saveuser(String mail, String password, String right,
			String workname) throws SQLException, InstantiationException,
			IllegalAccessException, ClassNotFoundException {
		DB.InsertUser(mail, workname, right, password);

	}

	public static boolean isSetupNTmanagerMail(String path) {
		String pathxml = path + File.separatorChar + "ntmanager.xml";
		File ntmangerFile = new File(pathxml);
		if (ntmangerFile.exists()) {
			return true;
		}
		return false;
	}

	public static void testMail(String mailbox, String user, String password,
			String smtphost) throws Exception {
		Properties props = System.getProperties();

		props.setProperty("mail.smtp.host", smtphost);
		props.setProperty("mail.smtp.auth", "true");
		Session.getDefaultInstance(props, null).setDebug(true);
		Authenticator auth = new smtpauthen(user, password);
		Session session = Session.getInstance(props, auth);
		MimeMessage message = new MimeMessage(session);

		message.setFrom(new InternetAddress(mailbox));
		message.addRecipient(Message.RecipientType.TO, new InternetAddress(
				mailbox));
		message.setSubject("Test Mail Box");
		message.setText("test");

		message.saveChanges();
		Transport transport = session.getTransport("smtp");

		Transport.send(message);
		transport.close();

	}

	public static String getCurrentUserFirstPage(String path, int right,
			String cookiename) throws DocumentException {

		SAXReader xreader = new SAXReader();

		Document xmldocment = xreader.read(path + File.separator
				+ "functionwork.xml");
		Element root = xmldocment.getRootElement();
		@SuppressWarnings("unchecked")
		Iterator<Element> itern = root.elementIterator();
		while (itern.hasNext()) {
			Element item = itern.next();
			if (Integer.parseInt(item.attributeValue("right")) != right) {
				continue;
			}
			if (item.attributeValue("url").compareToIgnoreCase(
					"editpssword.jsp") == 0) {
				return item.attributeValue("url") + "?user=" + cookiename;
			} else {
				return item.attributeValue("url");
			}
		}
		return path;

	}

	public static void SaveMailSetting(String mailbox, String user,
			String password, String smtp, String path) {

	}

	public static List<Userinfo> findAll() throws SQLException,
			InstantiationException, IllegalAccessException,
			ClassNotFoundException {
		ResultSet resut = SystemConfig.getInstance().getConnection()
				.createStatement().executeQuery("select * from userinfo");

		List<Userinfo> userinfo = new ArrayList<Userinfo>();
		while (resut.next()) {
			Userinfo userinfoitem = new Userinfo();
			userinfoitem.setId(resut.getLong("id"));
			userinfoitem.setmail(resut.getString("mail"));
			userinfoitem.setName(resut.getString("name"));
			userinfoitem.setpassword(resut.getString("password"));
			userinfoitem.setright(resut.getInt("userright"));
			userinfoitem.setmodifydate(resut.getTimestamp("modifydate"));
			userinfoitem.setFreeze(resut.getInt("freeze"));
			userinfo.add(userinfoitem);
		}
		return userinfo;

	}

	public static String getPassword() {
		String randompass = "1234567890abcdefghijklmnopqrstuvwxyz!@#$%^&*()";

		Random rand = new Random(Calendar.getInstance().getTimeInMillis());
		StringBuilder strbuilder = new StringBuilder();
		for (int i = 0; i < 8; i++) {
			strbuilder.append(randompass.charAt(Math.abs(rand.nextInt())
					% randompass.length()));

		}
		return strbuilder.toString();
	}

	public static void SendPasswordWithUserInfo(Userinfo userinfo) {

	}
}
